<?php
	namespace Util;
	
	class IMGUpload {
		/*允许使用的项为Think/Upload的参数项*/
		private $Handle = NULL;
		
		private $Thumb = NULL;
		/**
		压缩项使用说明
		ThumbAuto 1:跟随模式 2:子目录(格式:Ym[201607]) 3:默认压缩目录
		ThumbSize 压缩的大小
		ThumbRoot 根目录
		ThumbPath 目录路径
		 */
		private $config = array(
			'ThumbAuto' => 1,
			'ThumbSize' => array(150,150),
			'ThumbRoot' => './Cuisine/',
			'ThumbPath' => 'thumb/',
			'Thumb'     => false
			);
		/**
		 * [__construct 初始化使用]
		 * @Author   :seven
		 * @DateTime :2016-07-05T09:59:56+0800
		 * @Detail   :
		 * @param    [type]                    $sign [description]
		 */
		public function __construct($sign=false){
			$this->Handle = new \Think\Upload();
			$this->Handle->maxSize = 1024*1024 ;// 设置附件上传大小 (-1) 是不限值大小
		    $this->Handle->exts = array(
		    	'jpg', 'gif', 'png', 'jpeg'
		    );// 设置附件上传类型
		    $this->Handle->subName = array('date','Ym');
		    $this->Handle->savePath = 'Pic/';// 设置附件上传目
	        $this->Handle->replace = true; //存在同名文件是否是覆盖
	        $this->Handle->autoSub = true;

			if($sign){
				$this->Thumb = new \Think\Image();
			}
		}
		/**
		 * [__set 设置配置项]
		 * @Author   :seven
		 * @DateTime :2016-07-05T11:46:58+0800
		 * @Detail   :
		 * @param    [type]		$name  [配置名]
		 * @param    [type]		$value [配置值]
		 */
		public function __set($name,$value){
			if(isset($this->config[$name])){
				$this->config[$name] = $value;
				return ;
			}
	        $this->Handle->$name = $value;
 	    }
 	    /**
 	     * [upload 上传图片(并可选择压缩)]
 	     * @Author   :seven
 	     * @DateTime :2016-07-05T11:47:25+0800
 	     * @Detail   :
 	     * @return   [String]	[返回数据]
 	     */
 	    public function upload(){
 	    	$info = $this->Handle->upload();
 	    	$root = $this->Handle->rootPath;
 	    	foreach ($info as $k => $v) {
				$msg[$k]['path'] = "{$root}{$v['savepath']}{$v['savename']}";
				if(!empty($this->Thumb)){
					$name = explode('.', $v['savename']);
					$msg[$k]['thumb'] = "{$name[0]}_thumb.{$name[1]}";
				}
			}
			if(!empty($this->Thumb)){
				$msg = $this->ThumbHandle($msg);
			}

			return $msg;
 	    }

 	    private function ThumbHandle($info){
 	    	try {
 	    		if(!isset($info) || empty($info) || is_string($info)){
					return NULL;
				}
	 	    	$savePath = $this->config['ThumbRoot'].$this->config['ThumbPath'];

	 	    	if($this->config['ThumbAuto']){
	 	    		$savePath .= date('Ym').'/';
	 	    		$this->_check($savePath);
	 	    	}

	 	    	$size = $this->config['ThumbSize'];
	 	    	foreach ($info as $k => $v) {
	 	    		/*打开图片*/
					$this->Thumb->open($v['path']);
					// 一个最大为150*150
					$this->Thumb->thumb($size[0],$size[1])->save($savePath.$v['thumb']);
					$info[$k]['thumb'] = $savePath.$v['thumb'];
	 	    	}

	 	    	return $info;
 	    	} catch (Exception $e) {
 	    		E($e);
 	    	}
 	    }

 	    private function _check($dir){
 	    	if(!is_dir($dir)){
				mkdir($dir, 0777, true);
			}
 	    }
	}

	?>
